package com.dfa.islife;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.util.ByteArrayBuffer;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class IsLifeActivity extends Activity {
	
	Button spinCat, spinType, spinSearchCat, spinSearchDist;
	ListView listViewItem, listViewCat, listViewType, listViewSearchCat, listViewSearchDist;
	ArrayList<Type> listTypes = new ArrayList<Type>();
	ArrayList<String> listNameTypes = new ArrayList<String>();
	ArrayList<Item> listItems = new ArrayList<Item>();
	Gallery gallery;
	String[] listGallery = {"PAZARTESI", "SALI", "ÇARŞAMBA", "PERŞEMBE", "CUMA", "CUMARTESI", "PAZAR"};

	String weather = "<?xml version='1.0' encoding='utf-8' ?><weather><date>01 Temmuz 2011 Cum</date>"+
		"<temp>25°C</temp><icon>http://www.istanbullife.com.tr/images/HavaDurumu/30.gif</icon>"+
		"<condition>Parçalı Bulutlu</condition></weather>";
	int cat, type, item;
	int searchcat, searchdist;	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        spinCat = (Button)findViewById(R.id.main_spin_cat);
        spinType = (Button)findViewById(R.id.main_spin_type);
        spinSearchCat = (Button)findViewById(R.id.main_spin_search_cat);
        spinSearchDist = (Button)findViewById(R.id.main_spin_search_dist);
        
        listViewItem = (ListView)findViewById(R.id.main_listview_item);
        listViewCat = (ListView)findViewById(R.id.main_listview_cat);
        listViewType = (ListView)findViewById(R.id.main_listview_type);
        
        listViewSearchCat = (ListView)findViewById(R.id.main_listview_search_cat);
        listViewSearchDist = (ListView)findViewById(R.id.main_listview_search_dist);
        
        gallery = (Gallery)findViewById(R.id.main_gallery_text);
        
        cat = type = item = searchcat = searchdist = -1;
        
        getWeather();
        getTypes();
        
        ArrayAdapter<String> gAdapter = new ArrayAdapter<String>(this, R.layout.gtextview, listGallery);
        gallery.setAdapter(gAdapter);
        
        spinCat.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				ArrayAdapter<CharSequence> adapter2 = 
					ArrayAdapter.createFromResource(IsLifeActivity.this, R.array.array_cat, R.layout.textview);
		        listViewCat.setAdapter(adapter2);
				int vi = listViewCat.getVisibility();
				if (vi == View.VISIBLE) {
					listViewCat.setVisibility(View.INVISIBLE);
					listViewType.setVisibility(View.INVISIBLE);
				}
				else {
					listViewCat.setVisibility(View.VISIBLE);					
				}
			}
		});
        spinType.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				int vi = listViewType.getVisibility();
				if (vi == View.VISIBLE) listViewType.setVisibility(View.INVISIBLE);
				else if(listViewCat.getVisibility() == View.VISIBLE && cat != -1) listViewType.setVisibility(View.VISIBLE);
			}
		});
        
        spinSearchCat.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				ArrayAdapter<CharSequence> adapter2 = 
					ArrayAdapter.createFromResource(IsLifeActivity.this, R.array.array_cat, R.layout.textview);
		        listViewSearchCat.setAdapter(adapter2);
				int vi = listViewSearchCat.getVisibility();
				if (vi == View.VISIBLE) {
					listViewSearchCat.setVisibility(View.GONE);
					listViewSearchDist.setVisibility(View.GONE);
				}
				else {
					listViewSearchCat.setVisibility(View.VISIBLE);					
				}
			}
		});
        spinSearchDist.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				int vi = listViewSearchDist.getVisibility();
				if (vi == View.VISIBLE) listViewSearchDist.setVisibility(View.GONE);
				else if(listViewSearchCat.getVisibility() == View.VISIBLE && searchcat != -1) 
					listViewSearchDist.setVisibility(View.VISIBLE);
			}
		});
        
        listViewCat.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				cat = arg2;
				ArrayAdapter<String> adapter3 = 
					new ArrayAdapter<String>(IsLifeActivity.this, R.layout.textview, getTypes(Integer.toString(cat)));
	            listViewType.setAdapter(adapter3); 
	            listViewType.setVisibility(View.VISIBLE);
	            for(int i=0; i<arg0.getCount(); i++)
	            	arg0.getChildAt(i).setBackgroundColor(0xff666666);
	            arg1.setBackgroundColor(Color.RED);
			}
		});
        
        listViewType.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				type = arg2;
				listViewCat.setVisibility(View.INVISIBLE);
				listViewType.setVisibility(View.INVISIBLE);
				String[] temp = getResources().getStringArray(R.array.array_cat);
				spinCat.setText(temp[cat]);
				spinType.setText(listNameTypes.get(type).toString());
				new ShowItems(IsLifeActivity.this).execute(new Void[]{null});
			}
		});
        
        listViewSearchCat.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				searchcat = arg2;
	            for(int i=0; i<arg0.getCount(); i++)
	            	arg0.getChildAt(i).setBackgroundColor(0xff666666);
	            arg1.setBackgroundColor(Color.RED);
			}
		});
        
    }    
        
    public void getWeather(){
    	ImageView icon = (ImageView)findViewById(R.id.main_weather_icon);
    	TextView date = (TextView)findViewById(R.id.main_weather_date);
    	TextView temp = (TextView)findViewById(R.id.main_weather_temp);
    	TextView condition = (TextView)findViewById(R.id.main_weather_condition);
    	
    	try{
	    	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		    DocumentBuilder db;
			db = dbf.newDocumentBuilder();
		    InputSource is = new InputSource();
		    is.setCharacterStream(new StringReader(weather));
		    Document doc = db.parse(is);
		    NodeList nodes = doc.getElementsByTagName("weather"); 
		    for (int i = 0; i <nodes.getLength(); i++) {      	
		    	  Element element = (Element) nodes.item(i);
		      	  
		      	  NodeList node1 = element.getElementsByTagName("date");
		      	  Element ele1 = (Element) node1.item(0);
		      	  String s1 = getCharacterDataFromElement(ele1).trim();
		      	  
		      	  NodeList node2 = element.getElementsByTagName("temp");
		      	  Element ele2 = (Element) node2.item(0);
		      	  String s2 = getCharacterDataFromElement(ele2).trim();
		      	  
		      	  NodeList node3 = element.getElementsByTagName("icon");
		      	  Element ele3 = (Element) node3.item(0);
		      	  String s3 = getCharacterDataFromElement(ele3).trim();
		      	  
		      	  NodeList node4 = element.getElementsByTagName("condition");
		      	  Element ele4 = (Element) node4.item(0);
		      	  String s4 = getCharacterDataFromElement(ele4).trim();
		      	  
		      	  icon.setImageBitmap(getBitmapFromUrl(s3));
		      	  date.setText(s1);
		      	  temp.setText(s2);
		      	  condition.setText(s4);
		    }
    	}catch (Exception e) {
		}
    }
    public class ShowItems extends AsyncTask<Void, Void, Void> {
    	
    	private Context context;
    	
    	public ShowItems(Context c) {				
    		context = c;
    		listItems.clear();
    		listViewItem.setVisibility(View.INVISIBLE);
    	}
    	@Override
    	protected Void doInBackground(Void... arg0) {
    		String url = "http://www.istanbullife.com.tr/services/topten.aspx?category="+ cat + "&type=" + type;
    		try{
    			InputStream ist;
    			URL myURL = new URL(url);    		    
    		    URLConnection conn = myURL.openConnection();
    			ist = conn.getInputStream();
    			BufferedInputStream bis = new BufferedInputStream(ist);
    	    	
    			ByteArrayBuffer baf = new ByteArrayBuffer(1024);
    			int current = 0;
    			while((current = bis.read()) != -1){
    				baf.append((byte)current);
    			}
    			String myString = new String(baf.toByteArray());
    			
        	    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        	    DocumentBuilder db;
        		db = dbf.newDocumentBuilder();
        	    InputSource is = new InputSource();
        	    is.setCharacterStream(new StringReader(myString));
        	    Document doc = db.parse(is);
        	    NodeList nodes = doc.getElementsByTagName("item"); 
        	    for (int i = 0; i <nodes.getLength(); i++) {      	
        	    	  Element element = (Element) nodes.item(i);
        	      	  
        	      	  NodeList idNode = element.getElementsByTagName("id");
        	      	  Element idEle = (Element) idNode.item(0);
        	      	  String id = getCharacterDataFromElement(idEle).trim();
        	      	  
        	      	  NodeList titleNode = element.getElementsByTagName("title");
        	      	  Element titleEle = (Element) titleNode.item(0);
        	      	  String title = getCharacterDataFromElement(titleEle).trim();
        	      	  
        	      	  NodeList thumbNode = element.getElementsByTagName("thumb");
        	      	  Element thumbEle = (Element) thumbNode.item(0);
        	      	  String thumb = getCharacterDataFromElement(thumbEle).trim();
        	      	  
        	      	  NodeList textNode = element.getElementsByTagName("text");
        	    	  Element textEle = (Element) textNode.item(0);
        	    	  String text = getCharacterDataFromElement(textEle).trim(); 
        	    	  
        	    	  listItems.add(new Item(id, title, thumb, text));
        	    }
    		    ist.close();
    	    }catch (Exception e) {
    	        e.printStackTrace();
    	    } 
    	    catch(OutOfMemoryError o){
    		}
    		return null;
    	}
    	 
    	@Override
    	protected void onPostExecute(Void result) {
    		listViewItem.setAdapter(new ItemAdapter(context));
    		listViewItem.setVisibility(View.VISIBLE);
    	}
    }
    
    public class ViewHolder {
    	ImageView thumb;
    	TextView title;
    	TextView text;
    }
    
    public class ItemAdapter extends BaseAdapter {
		private Context context;
		private LayoutInflater mInflater;
		
		public ItemAdapter(Context c) {
			this.context = c;
			this.mInflater = LayoutInflater.from(context);
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			System.gc();
			final int index = position;
			final ViewHolder holder;
			convertView = mInflater.inflate(R.layout.row_item, null);
			holder = new ViewHolder();
			holder.thumb = (ImageView)convertView.findViewById(R.id.thumb);
			holder.title = (TextView)convertView.findViewById(R.id.title);
			holder.text = (TextView)convertView.findViewById(R.id.text);
			
			holder.thumb.setImageBitmap(getBitmapFromUrl(listItems.get(index).thumb));
			holder.title.setText(listItems.get(index).title);
			holder.text.setText(listItems.get(index).text);
			
			return convertView;
		}		
		
		@Override
		public int getCount() {
			return listItems.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}
		@Override
		public long getItemId(int position) {
			return 0;
		}
	} 
    
    public Bitmap getBitmapFromUrl(String url){
		Bitmap bm = null;
		try {
			URL myImageURL = new URL(url); 		    
		    URLConnection conn = myImageURL.openConnection();
			InputStream input = conn.getInputStream();
			bm = BitmapFactory.decodeStream(input);
			input.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bm;
	}
    public void getTypes(){    	
    	try{
			InputStream ist;
			URL myURL = new URL(getString(R.string.link_type));    		    
		    URLConnection conn = myURL.openConnection();
			ist = conn.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(ist);
	    	
			ByteArrayBuffer baf = new ByteArrayBuffer(1024);
			int current = 0;
			while((current = bis.read()) != -1){
				baf.append((byte)current);
			}
			String myString = new String(baf.toByteArray());
			
    	    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    	    DocumentBuilder db;
    		db = dbf.newDocumentBuilder();
    	    InputSource is = new InputSource();
    	    is.setCharacterStream(new StringReader(myString));
    	    Document doc = db.parse(is);
		    NodeList nodes = doc.getElementsByTagName("type"); 
		    for (int i=0; i<nodes.getLength(); i++) {      	
		    	  Element element = (Element) nodes.item(i); 		    	  
		      	  String num = nodes.item(i).getAttributes().getNamedItem("num").getNodeValue();		      	  
		      	  NodeList iconNode = element.getElementsByTagName("typeId");
		      	  
		      	  for (int j=0; j<iconNode.getLength(); j++) {
		      		  
		      		  NodeList idNode = element.getElementsByTagName("typeId");
			      	  Element idEle = (Element) idNode.item(j);
			      	  String id = getCharacterDataFromElement(idEle).trim();
			      	  
			      	  NodeList nameNode = element.getElementsByTagName("name");
			      	  Element nameEle = (Element) nameNode.item(j);
			      	  String name = getCharacterDataFromElement(nameEle).trim();
			      	  
			      	  listTypes.add(new Type(num, id, name));
		      	  }
		    }
		    ist.close();
		    System.gc();
	    }catch (Exception e) {
	        e.printStackTrace();
	    }
    }
    
    public void getDists(){    	
    	try{
			InputStream ist;
			URL myURL = new URL(getString(R.string.link_dist));    		    
		    URLConnection conn = myURL.openConnection();
			ist = conn.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(ist);
	    	
			ByteArrayBuffer baf = new ByteArrayBuffer(1024);
			int current = 0;
			while((current = bis.read()) != -1){
				baf.append((byte)current);
			}
			String myString = new String(baf.toByteArray());
			
    	    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    	    DocumentBuilder db;
    		db = dbf.newDocumentBuilder();
    	    InputSource is = new InputSource();
    	    is.setCharacterStream(new StringReader(myString));
    	    Document doc = db.parse(is);
		    NodeList nodes = doc.getElementsByTagName("type"); 
		    for (int i=0; i<nodes.getLength(); i++) {      	
		    	  Element element = (Element) nodes.item(i); 		    	  
		      	  String num = nodes.item(i).getAttributes().getNamedItem("num").getNodeValue();		      	  
		      	  NodeList iconNode = element.getElementsByTagName("typeId");
		      	  
		      	  for (int j=0; j<iconNode.getLength(); j++) {
		      		  
		      		  NodeList idNode = element.getElementsByTagName("typeId");
			      	  Element idEle = (Element) idNode.item(j);
			      	  String id = getCharacterDataFromElement(idEle).trim();
			      	  
			      	  NodeList nameNode = element.getElementsByTagName("name");
			      	  Element nameEle = (Element) nameNode.item(j);
			      	  String name = getCharacterDataFromElement(nameEle).trim();
			      	  
			      	  listTypes.add(new Type(num, id, name));
		      	  }
		    }
		    ist.close();
		    System.gc();
	    }catch (Exception e) {
	        e.printStackTrace();
	    }
    }
    
	public ArrayList<String> getTypes(String pos){
		listNameTypes.clear();
    	for(int i=0; i<listTypes.size(); i++){
    		if(listTypes.get(i).num.equals(pos))
    			listNameTypes.add(listTypes.get(i).name);
    	}
    	return listNameTypes;
    }
    public String getCharacterDataFromElement(Element e) {
        Node child = e.getFirstChild();
        if (child instanceof CharacterData) {
           CharacterData cd = (CharacterData) child;
           return cd.getData();
        }
        return "";
    } 
    
    public class Type{
    	String num;
    	String id;
    	String name;
    	
    	public Type(String num, String id, String name){
    		this.num = num;
    		this.id = id;
    		this.name = name;
    	}
    }
    
    public class Item{
    	String id;
    	String title;
    	String thumb;
    	String text;
    	
    	public Item(String id, String title, String thumb, String text){
    		this.id = id;
    		this.title = title;
    		this.thumb = thumb;
    		this.text = text;
    	}
    }
    @Override
	 public boolean onKeyDown(int keyCode, KeyEvent event)  {
	     if (keyCode == KeyEvent.KEYCODE_BACK) {
	         finish();
	         return true;
	     }
	     return super.onKeyDown(keyCode, event);
	 }
}